// =================================================================
// File: link.cpp
// Desc: Contains function for linking files
// =================================================================

// =================================================================
// INCLUDES
// =================================================================

#include <string>
#include "FSManager.h"
#include "commands.h"
#include "Directory.h"
#include "Inode.h"
#include <ctime>

using namespace std;

// =================================================================
// FUNCTIONS
// =================================================================

// =================================================================
// Name: link
// Desc: Makes a link of src_path at dest_path
// Args: string src_path - the path of the src file for linking
//	 string dest_path - the path of to put the new link of the src file
//       FSManager* fsm - pointer to active FSManager object
// =================================================================
void link(string src_path, string dest_path, FSManager *fsm){
 
  size_t found;
  Directory *src_dir,*dest_dir;
  string filename;
  Inode *node;
  bool isDir = false;

  if(src_path[src_path.length()-1] == '/'){
    src_path.erase(src_path.length()-1,1);
  }
  if(dest_path[dest_path.length()-1] == '/'){
    dest_path.erase(dest_path.length()-1,1);
  }

  found = src_path.find_last_of("/");
  if(found == string::npos){
    src_dir = fsm->GetCurrentDirectory();
  }
  else{
    src_dir = fsm->ReadDirectory(src_path.substr(0,found));
  }
  filename = src_path.substr(found+1);

  int src_inode_index = src_dir->GetEntry(filename);
  if(src_inode_index == -1){
  src_inode_index = src_dir->GetEntry((filename+"/"));
  isDir = true;
  }

  node = fsm->ReadInode(src_inode_index);
  node->SetNumLinks(node->GetNumLinks()+1);
  node->SetModified(time(0));

  fsm->WriteInode(node,src_inode_index);
  delete node;

  filename = "";

  found = dest_path.find_last_of("/");
  
  if(found == string::npos){
    dest_dir = fsm->GetCurrentDirectory();
  }
  else{
    dest_dir = fsm->ReadDirectory(dest_path.substr(0,found));
  }

  filename = dest_path.substr(found+1);
 if(isDir){
  filename += "/";
 }

 //cout << src_inode_index << endl;

 /*Directory *newDir = new Directory(src_inode_index,dest_dir->GetEntry("../"));
 newDir->SetInodeIndex(src_inode_index);
  cout << "WRITE newDir" << endl;
  fsm->WriteDirectory(newDir);

  //cout << "new_dir: " << newDir->GetEntry("../") << endl;
 //cout << "dest_dir: " << dest_dir->GetEntry("../") << endl;
*/
  dest_dir->InsertEntry(filename,src_inode_index);

  fsm->WriteDirectory(dest_dir);

  if(src_dir->GetInodeIndex() != fsm->GetCurrentDirectory()->GetInodeIndex()){
    delete src_dir;
  }
  if(dest_dir->GetInodeIndex() != fsm->GetCurrentDirectory()->GetInodeIndex()){
    delete dest_dir;
  }
  
  cout << "Link to " << src_path << " created at " << dest_path << endl;
}

